<template>
    <!-- 选项 -->
    <div class="analysis-chart-options">
        <!-- 客户自动填充框 -->
        <el-autocomplete
            v-model="quickChartCustomer"
            :fetch-suggestions="queryCustomerSearch"
            clearable
            style="width: 260px"
            placeholder="请选择客户"
            @select="handleCustomerSelect"
            @clear="handCustomerClear"
        />
        <!-- 产品自动填充框 -->
        <el-autocomplete
            v-model="quickChartProduct"
            :fetch-suggestions="queryProductSearchByCustomerId"
            clearable
            style="width: 260px"
            placeholder="请选择产品"
            @select="handleProductSelect"
        />
        <!-- 展示模式 -->
        <el-select v-model="quickChartSelect" placeholder="请选择查看模式" style="width: 200px" @change="handleSelectChange">
            <el-option label="月" value="month" />
            <el-option label="天" value="day" />
            <el-option label="年" value="year" />
        </el-select>
        <!-- 时间段选择 -->
        <el-date-picker v-model="quickChartDateRange" :type="quickChartDateMode" range-separator="-" />
    </div>
    <!-- 客户发货分析 -- 图表容器 -->
    <div ref="chartContainer" class="quick-chart-container"></div>
</template>

<script setup lang="ts">
import { Chart } from '@antv/g2';
import { getCustomerProductOutbound } from '@/api/outbound';
import { useTemplateRef } from 'vue';
import { useSystemStore } from '@/store/modules/system';

const useSystem = useSystemStore();
// 表格显示宽度
const quickChartContainerWidth = computed(() => {
    return useSystem.config.isCollapse ? 'calc(100vw - 84px)' : 'calc(100vw - 220px)';
});

const customerList = defineModel<AjaxResponse['customerList']>('customerList', { required: true });
const productList = defineModel<(AjaxResponse['productList'][number] & { value: string; customerId: string })[]>('productList', { required: true });

/* ******************************客户发货分析属性/方法****************************** */
// 客户发货分析 -- 客户信息
const quickChartCustomer = ref();
// 客户Id
const quickChartCustomerId = ref();
// 客户过滤
const queryCustomerSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (customer: (typeof customerList.value)[number]) => {
            return new RegExp(queryString).test(customer.customerName);
        };
    };

    const results = queryString ? customerList.value.filter(createFilter(queryString)) : customerList.value;
    // call callback function to return suggestions
    cb(results);
};
// 处理客户选择事件
const handleCustomerSelect = (item: Record<string, any>) => {
    quickChartCustomerId.value = item._id;
};
// 处理客户清空事件
const handCustomerClear = () => {
    quickChartCustomerId.value = '';
    quickChartProduct.value = '';
};
// 处理客户清空监听
watch(
    () => quickChartCustomer.value,
    (newValue) => {
        if (newValue == '') {
            quickChartCustomerId.value = '';
            quickChartProduct.value = '';
        }
    }
);

// 客户发货分析 -- 客户的产品选择
const quickChartProduct = ref();
// 产品过滤限制客户Id
const queryProductSearchByCustomerId = (queryString: string, cb: any) => {
    if (!quickChartCustomerId.value) {
        ElMessage.error('请先选择客户');
        cb();
        return;
    } else {
        // 过滤器
        const createFilter = (queryString: string) => {
            return (product: (typeof productList.value)[number]) => {
                return new RegExp(queryString).test(product.productName);
            };
        };

        const results = queryString
            ? productList.value.filter((i) => i.customerId === quickChartCustomerId.value).filter(createFilter(queryString))
            : productList.value.filter((i) => i.customerId === quickChartCustomerId.value);
        // call callback function to return suggestions
        cb(results);
    }
};
// 处理产品选择
const handleProductSelect = (item: Record<string, any>) => {
    // 请求数据
    getCustomerProductOutbound(
        quickChartCustomerId.value,
        item._id,
        quickChartSelect.value,
        quickChartDateRange.value[0],
        quickChartDateRange.value[1]
    ).then((res) => {
        // 清空数据集
        dataSet.length = 0;
        // 处理数据
        res.data.forEach((item) => {
            dataSet.push({
                month: item.month,
                quantity: item.quantity,
            });
        });
        // 渲染图表
        updateBarChart();
    });
};

// 客户发货分析 -- 模式选择
const quickChartSelect = ref<'month' | 'year' | 'day'>('month');
const handleSelectChange = (value: any) => {
    // 默认值为12个月
    if (value == 'month') {
        quickChartDateMode.value = 'monthrange';
        quickChartDateRange.value = [new Date(new Date(new Date()).setFullYear(new Date().getFullYear() - 1)), new Date()];
    }

    // 默认值为5年
    if (value == 'year') {
        quickChartDateMode.value = 'yearrange';
        quickChartDateRange.value = [new Date(new Date(new Date()).setFullYear(new Date().getFullYear() - 5)), new Date()];
    }

    // 默认值为1个月的天数
    if (value == 'day') {
        quickChartDateMode.value = 'daterange';
        // 默认值为1个月的天数
        quickChartDateRange.value = [new Date(new Date(new Date()).setDate(new Date().getDate() - 30)), new Date()];
    }
};

// 时间筛选模式
const quickChartDateMode = ref<'monthrange' | 'daterange' | 'yearrange'>('monthrange');
// 客户发货分析 -- 时间筛选
const quickChartDateRange = ref<[Date, Date]>([new Date(new Date(new Date()).setFullYear(new Date().getFullYear() - 1)), new Date()]);

/* ******************************客户发货图标属性/方法****************************** */
let chart: Chart;
// 图表容器
const chartContainerRef = useTemplateRef('chartContainer');
// 数据集
const dataSet = reactive<{ month: string; quantity: number }[]>([]);

// 渲染图表
const renderChart = () => {
    // 图表实例
    const chart = new Chart({
        container: chartContainerRef.value!,
        // 自动调整尺寸
        autoFit: true,
    });

    // 可视化声明
    chart
        .interval()
        .data(dataSet)
        .encode('x', 'month')
        .encode('y', 'quantity')
        .encode('key', 'genre')
        .axis('x', { title: '时间' })
        .axis('y', { title: '数量' })
        .tooltip({ name: '数量', channel: 'y' })
        .label({
            render: (_text, datum) => {
                return datum.quantity == 0
                    ? `&nbsp;`
                    : `<div style="left:50%;top:-20px;position:relative;font-size:14px;">
                            <span>${datum.quantity}</span>
                        </div>`;
            },
        });
    // 渲染可视化
    chart.render();

    return chart;
};

// 更新条形图的数据
function updateBarChart() {
    // 获得 Interval Mark
    const interval = chart.getNodesByType('interval')[0];
    // console.log('🚀 ~ updateBarChart ~ interval:', interval);

    // 模拟并且更新 Interval 的数据
    // @ts-ignore
    interval.data(dataSet);

    // 重新渲染
    chart.render();
}

onMounted(() => {
    chart = renderChart();
});
</script>

<style scoped lang="scss">
.analysis-chart-options {
    display: flex;
    align-items: center;
    gap: 10px;
    height: 40px;
}

.quick-chart-container {
    height: calc(100vh - 150px);
    width: v-bind(quickChartContainerWidth);
}
</style>
